import time

from django.db.models import Q
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.generics import ListAPIView
from rest_framework.pagination import PageNumberPagination
from unicodedata import category

from courses import models, ser
from utils.kafka_producer import send_kafka_message


# Create your views here.


class MyPagination(PageNumberPagination):
    page_size = 10
    page_size_query_param = 'size'
    page_query_param = 'page'
    max_page_size = 10


class CourseView(ListAPIView):
    queryset = models.Course.objects.all()
    serializer_class = ser.CourseSerializer
    pagination_class = MyPagination

    # 有查询需要重写get_queryset方法
    def get_queryset(self):
        # 1.基础的查询条件 上架课程 status = 1
        query = Q(status=1)
        # 2.获取前端传递的参数，拼接我的其他查询条件
        nav_name = self.request.query_params.get('nav_name')
        cate = self.request.query_params.get('cate')
        price_range = self.request.query_params.get('price_range')
        sort = self.request.query_params.get('sort')
        keyword = self.request.query_params.get('keyword')
        # 有可能为空 如果为空的话 就不作为查询条件
        if nav_name:
            query &= Q(nav_relations__nav_category__name=nav_name)
        if cate:
            query &= Q(categories__id=cate)
        if price_range:
            query &= Q(course_type=price_range)
        if sort:
            return self.queryset.filter(query).select_related('teacher').order_by("-" + sort)
        if keyword:
            query &= (Q(name__icontains=keyword) | Q(description__icontains=keyword) | Q(brief__icontains=keyword) |
                      Q(teacher__name__icontains=keyword))
        queryset = self.queryset.filter(query).select_related("teacher")
        user = self.request.user
        data = {
            "user_id": user.id or None,
            "search_time": time.strftime("%Y-%m-%d %H:%M:%S"),
            "nav_name": nav_name or None,
            "category": cate or None,
            "keywords": keyword or None,
            "sort_by": sort or None,
            "price_range": price_range or None,
            "results": []  # ,搜索结果存储课程ID
        }
        for item in queryset:
            data["results"].append(item.id)
        send_kafka_message("search7a_topic", 'views', data)
        return self.queryset.filter(query).select_related('teacher')


class CourseDetailView(APIView):
    def get(self, request):
        pk = request.query_params.get('id')
        if not pk:
            return Response({
                'code': 400,
                'msg': '参数不全'
            })
        info = models.Course.objects.filter(id=pk, is_show=True, is_del=False).first()
        if not info:
            return Response({
                'code': 400,
                'msg': '课程不存在'
            })
        res = ser.CourseDetailSerializer(info).data
        # chapters = models.CourseChapter.objects.filter(course_id=ids)
        user = request.user
        data = {
            'user': user.id or None,
            'username': user.username or None,
            "course": pk,
            'coursename': info.name,
        }
        send_kafka_message('view7a_topic', 'views', data)
        return Response({
            'code': 200,
            'msg': 'ok',
            'data': res
        })
